package nullby.yoga.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;

import nullby.yoga.R;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import android.widget.Toast;

public class FileManager {

	public static final String DIR_NAME = "EuropeanYoga";

	/**
	 * Get path for the file on external storage. If external storage is not
	 * currently mounted this will fail.
	 * 
	 * @param filename
	 * @return
	 */
	public static Boolean isExists(final String filename) {
		File file = new File(Environment.getExternalStorageDirectory()
				.getPath().concat(File.separator).concat(DIR_NAME)
				.concat(File.separator), filename);

		if (file != null) {
			return file.exists();
		}
		return false;

	}

	public static Long getFileSize(final String filename) {
		File file = new File(Environment.getExternalStorageDirectory()
				.getPath().concat(File.separator).concat(DIR_NAME)
				.concat(File.separator), filename);
		return getFileSize(file);
	}

	public static Long getFileSize(final File file) {
		return file.length();
	}

	public static String getFilePath(String filename) {
		return Environment.getExternalStorageDirectory().getPath()
				.concat(File.separator).concat(PrefManager.DIR_NAME)
				.concat(File.separator).concat(filename);
	}

	public static void copyFileFromRawIntoSd(final Context context,
			final Integer idResource, final String nameFile) {
		File dir = new File(Environment.getExternalStorageDirectory().getPath()
				.concat(File.separator).concat(DIR_NAME).concat(File.separator));
		if (!dir.exists()) {
			dir.mkdirs();
		}

		File file = new File(Environment.getExternalStorageDirectory()
				.getPath().concat(File.separator).concat(DIR_NAME)
				.concat(File.separator), nameFile);
		InputStream is = null;
		OutputStream os = null;
		try {
			is = context.getResources().openRawResource(idResource);
			os = new FileOutputStream(file);
			byte[] data = new byte[is.available()];
			is.read(data);
			os.write(data);
		} catch (IOException e) {
			Log.w("ExternalStorage", "Error writing " + file, e);
//			Toast.makeText(context, "ERROR INIT", 0).show();
		} finally {
			try {
				is.close();
				os.close();
			} catch (IOException e) {
			}
		}
	}

}
